package com.example.day11.visibility;

public class VolatitleDemo {

    /**
     * 保证 x具有可见性
     * 如何做到“可见性”  write-x刷回主存   主存x发生变化 -read线程立即从主存拉去最新x
     */
    private  volatile int x;

    //线程负责读
    public  void read(){
        while (x!=5){

            /**
             * 死循环。。
             *
             *
             */
        }
        if(x==5){
            System.out.println("read....");
        }
    }

    //线程负责写
    public  void  write(){
        x=5;
    }


}


class  VolatileDemoTest{
    public static void main(String[] args) {
        VolatitleDemo v=new VolatitleDemo();
        Thread t1=new Thread(()->v.write());
        Thread t2=new Thread(()->v.read());

        //先读
        t2.start();

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //在写
        t1.start();
    }
}
